package cn.jwcat.service.impl;

import cn.jwcat.entity.Menu;
import cn.jwcat.mapper.MenuMapper;
import cn.jwcat.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 菜单 服务实现类
 * </p>
 *
 * @author 橙子味的猫
 * @since 2023-04-09
 */
@Transactional
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

	@Override
	public List<Menu> getMenuListByUserId(Integer userId) {
		// 一级菜单
		List<Menu> menuList = this.getBaseMapper().getMenuListByUserId(userId, 0);
		// 子菜单
		setMenuChildrenByUserId(userId, menuList);
		return menuList;
	}

	private void setMenuChildrenByUserId(Integer userId, List<Menu> menuList) {
		if (menuList != null) {
			for (Menu menu : menuList) {
				List<Menu> subMenuList = this.getBaseMapper()
					.getMenuListByUserId(userId, menu.getMenuId());
				menu.setChildren(subMenuList);
				// 递归
				setMenuChildrenByUserId(userId, subMenuList);
			}
		}
	}
}
